//package com.ruoyi.ahs.scheduler;
//
//import java.util.List;
//import java.util.Map;
//import java.util.concurrent.ConcurrentHashMap;
//import java.util.concurrent.ExecutorService;
//import java.util.concurrent.Executors;
//import java.util.concurrent.TimeUnit;
//
//import com.alibaba.fastjson2.JSONObject;
//import com.ruoyi.ahs.cache.AhsCache;
//import com.ruoyi.ahs.util.AhsUtils;
//import com.ruoyi.ahs.util.RushTaskDto;
//import com.ruoyi.ahs.util.WeChatBotMessageSender;
//import com.ruoyi.common.exception.base.BaseException;
//import com.ruoyi.system.domain.RushConfig;
//import com.ruoyi.system.domain.ahs.*;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.stereotype.Component;
//import org.springframework.util.CollectionUtils;
//
//@Slf4j
//@Component
//public class RushTaskMonitor {
//
//    private ExecutorService executorService;
//    // 使用 ConcurrentHashMap 存储任务及其对应的线程，便于管理线程的启动和停止
//    private Map<Long, Thread> taskThreadMap = new ConcurrentHashMap<>();
//
//    private int status = 0; //0 停止 1启用
//
//    public void stop() {
//        if (status == 1) {
//            log.info("销毁RushTaskMonitor线程池。。。。。。");
//            if (executorService != null && !executorService.isShutdown()) {
//                executorService.shutdownNow();
//            }
//            executorService = null;
//            taskThreadMap.clear();
//        }
//        status = 0;
//    }
//
//    public void start() {
//        if (status == 0 || executorService == null || executorService.isShutdown()) {
//            log.info("创建RushTaskMonitor线程池。。。。。。");
//            executorService = Executors.newCachedThreadPool();
//        }
//        List<RushTaskDto> tasks = AhsCache.getRushTaskCache();
//        for (RushTaskDto task : tasks) {
//            // 为每个任务创建一个监控线程
//            if (taskThreadMap.containsKey(task.getId())) {
//                continue;
//            }
//            Thread thread = new Thread(new RushTaskMonitorThread(task));
//            executorService.submit(thread);
//            taskThreadMap.put(task.getId(), thread);
//        }
//        status = 1;
//        log.info("初始化RushTaskMonitor线程池完成！");
//    }
//
//
//    private class RushTaskMonitorThread implements Runnable {
//        private RushTaskDto task;
//
//        public RushTaskMonitorThread(RushTaskDto task) {
//            this.task = task;
//        }
//
//        @Override
//        public void run() {
//            while (!Thread.currentThread().isInterrupted()) {
//                try {
//                    // 发起请求监控任务
//                    monitorTask(task);
//                    TimeUnit.MILLISECONDS.sleep(AhsCache.reqInterval);
//                } catch (InterruptedException e) {
//                    // 收到中断信号，退出循环
//                    Thread.currentThread().interrupt();
//                    break;
//                }
//            }
//        }
//
//
//        /**
//         * 商品下单
//         */
//        private OrderResult createOrder(Product product) {
//            List<Discount> discountList = product.getDiscountList();
//            String discountCode = null;
//            if (!CollectionUtils.isEmpty(discountList)) {
//                discountCode = discountList.stream()
//                        .filter(d -> "1001".equals(d.getDiscountType()))
//                        .map(Discount::getCode)
//                        .findFirst()
//                        .orElse(discountList.get(0).getCode());
//            }
//            Sensors sensors = AhsCache.getSensors();
//            RushConfig config = AhsCache.getCurrentConfig();
//            Order orderDTO = new Order();
//            orderDTO.setProductSerialNo(product.getProductNo());
//            orderDTO.setCityId(config.getCityId());
//            orderDTO.setActivityCode(discountCode != null ? discountCode : config.getActivityCode());
//            orderDTO.setPickupType(config.getPickupType());
//            orderDTO.setAddressId(config.getAddressId() != null ? config.getAddressId() : AhsCache.getAddressId());
//            orderDTO.setSensors(sensors);
//            return AhsUtils.createOrder(orderDTO);
//        }
//
//        private void monitorTask(RushTaskDto task) {
//            // 这里是对任务进行监控的具体逻辑，需要根据具体需求实现
//            // 例如：发送 HTTP 请求等操作，暂时未实现具体代码
//            try {
//                ProductSearch productSearch = task.getProductSearch();
//                SearchResult searchResult = AhsUtils.search(productSearch);
//                if (searchResult.isSuccess()) {
//                    List<Product> productList = searchResult.getData();
//                    if (CollectionUtils.isEmpty(productList)) {
//                        return;
//                    }
//                    for (Product product : productList) {
//                        if (product != null) {
//                            log.info("抢购消费者 {} 正在下单产品: {}", Thread.currentThread().getName(), product);
//                            OrderResult orderResult = createOrder(product);
//                            if (orderResult.isSuccess()) {
//                                WeChatBotMessageSender.sendMessage(String.format("抢购商品成功！订单号:%s", orderResult.getData()), null);
//                            } else {
//                                WeChatBotMessageSender.sendMessage(String.format("抢购失败！原因:%s", orderResult.getResultMessage()), 1);
//                            }
//                            //抢购时间
//                            Thread.sleep(AhsCache.ordInterval);
//                        }
//                    }
//                } else {
//                    WeChatBotMessageSender.sendMessage("抢购失败" + JSONObject.toJSONString(searchResult));
//                    throw new BaseException("抢购失败", JSONObject.toJSONString(searchResult));
//                }
//            } catch (InterruptedException e) {
//                Thread.currentThread().interrupt();
//                log.warn("线程被中断，线程名称：{}", Thread.currentThread().getName());
//            } catch (Exception e) {
//                //WeChatBotMessageSender.sendMessage("抢购异常，异常信息：" );
//                log.error("抢购异常，异常信息：", e);
//            }
//        }
//    }
//}